// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.account

import android.content.Context
import android.content.Context.MODE_PRIVATE
import androidx.core.content.edit


data class Client(val id: String, val secret: String, val authEndpoint: String) {
	companion object {
		const val PREFERENCES_NAME = "oidc_client"
		const val KEY_ID = "id"
		const val KEY_SECRET = "secret"
		const val KEY_ENDPOINT = "auth_endpoint"
		const val KEY_VERSION = "version"
		const val VERSION = 0

		fun load(context: Context): Client? {
			val preferences = context.getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE)
			val secret = preferences.getString(KEY_SECRET, null)
			val id = preferences.getString(KEY_ID, null)
			val authEndpoint = preferences.getString(KEY_ENDPOINT, null)
			val version = preferences.getInt(KEY_VERSION, -1)
			if (version != VERSION) {
				reset(context)
				// TODO don't logout forcibly
				return null
			}
			return if (secret != null && id != null && authEndpoint != null) {
				Client(id, secret, authEndpoint)
			} else {
				null
			}
		}

		fun reset(context: Context) {
			context.getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE).edit {
				clear()
			}
		}
	}

	fun save(context: Context) {
		context.getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE).edit {
			putString(KEY_ID, id)
			putString(KEY_SECRET, secret)
			putString(KEY_ENDPOINT, authEndpoint)
			putInt(KEY_VERSION, VERSION)
		}
	}
}